/**
 * Copyright (c) 2009 BBM AG
 * Melsungen, Germany
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of 
 * BBM AG ("Confidential Information").  You shall not disclose such 
 * Confidential Information and shall use it only in accordance with 
 * the terms of the license agreement you entered into with BBM AG.
 * 
 * Created on: 09.03.2009
 * Last modified: $Date$
 * 
 * $HeadURL$
 * $Revision$
 */
package de.riceman.simpleGo.main;

public class BitMatrixFactory {

	private static BitMatrixFactory instance;
	
	private BitMatrix[] hs;
	private boolean[] used;
	private int number;

	
	private BitMatrixFactory(int number) {
		this.number = number;
		
		hs = new BitMatrix[number];
		used = new boolean[number];
	}
	
	public static BitMatrixFactory getInstance() {

		return instance;
	}
	
	public static void init(int number) {
		if (instance == null) {
			instance = new BitMatrixFactory(number);
		}
	}
	
	public BitMatrix getNewBitMatrix(int rows, int cols) {
		
		for (int i = 0; i < number; i++) {

			if (used[i] == false) {
				
				if(hs[i] == null) {
					hs[i] = new BitMatrix(rows, cols);
					used[i] = true;
					return hs[i];					
				}
				if(hs[i].getRows() == rows && hs[i].getColumns() == cols) {
					used[i] = true;
					return hs[i];
				}
			}
		}
		
		//if we reach this point, no free space or free BitMatrix with the correct size has been found.
		System.out.println("Allocating " + Integer.toString(number) + " additional BitMatrices.");
		
		BitMatrix[] hs_new = new BitMatrix[number*2];
		boolean[] used_new = new boolean[number*2];
		
		for (int i = 0; i < number; i++) {
			hs_new[i] = hs[i];
			used_new[i] = used[i];
		}
		for (int i = number; i < (number*2); i++) {
			used_new[i] = false;
		}
		//remember the first new entry
		int newBitMatrix = number;

		//replace array
		hs = hs_new;
		used = used_new;
		number *= 2;
		
		used[newBitMatrix] = true;
		hs[newBitMatrix] = new BitMatrix(rows, cols);		
		
		return hs[newBitMatrix];
	}
	
	public void dispose(BitMatrix m) {
		
		for (int i = 0; i < number; i++) {
			if (hs[i] == m) {
				
				used[i] = false;
				hs[i].reset();
				break;
			}
		}
	}
}
